//
//  AppDelegate.m
//  51-Tour
//
//  Created by xiang ying on 14-3-17.
//  Copyright (c) 2014年 xiang ying. All rights reserved.
//

#import "AppDelegate.h"
#import "PKRevealController.h"
#import "LeftMenuViewController.h"
#import "RightMenuViewController.h"
#import "CenterMapViewController.h"
#import "HelpScrollView.h"
#import "MobClick.h"
#import "ServiceManage.h"
#import "SVProgressHUD.h"

typedef enum {
	NotReachable = 0,
	ReachableViaWiFi,
	ReachableViaWWAN
} NetworkStatus;

#define kReachabilityChangedNotification @"kNetworkReachabilityChangedNotification"

BMKMapManager* _mapManager;


@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    if (![ServiceManage checkNet]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[[DataCenter instance] getStringForKey:@"Tips"] message:@"当前没有网络，将不能很好的体验该应用" delegate:nil cancelButtonTitle:[[DataCenter instance] getStringForKey:@"Sure"] otherButtonTitles: nil];
        [alert show];
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(netChanged:) name:kReachabilityChangedNotification object:nil];
    _mapManager = [[BMKMapManager alloc]init];
	BOOL ret = [_mapManager start:@"xUqjXCqSdpHMFGqLmzqwkizX" generalDelegate:self];
	if (!ret) {
		NSLog(@"manager start failed!");
	}
    [WXApi registerApp:wxKey];
    _tencentOAuth = [[TencentOAuth alloc] initWithAppId:qqKey andDelegate:self];
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    
    [UIManagement shareInstance];
    [self.window makeKeyAndVisible];

    if ([[DataCenter instance] isFirstload]) {
        HelpScrollView *help = [[HelpScrollView alloc] initWithLanguage:YES];
        [self.window addSubview:help];
    }
    
    if ([[DataCenter instance] user].userPhone) {
        //
        [SVProgressHUD showWithStatus:[[DataCenter instance] getStringForKey:@"loading"]];
        [ServiceManage setRegisterRequestInfo:@{@"Mobile":[[DataCenter instance] user].userPhone,@"ValidateCode":[DataCenter instance].user.code} completion:^(RespondDTO *respond) {

            if (respond.flag == respond_success) {
                NSLog(@"login success");
                [SVProgressHUD showSuccessWithStatus:[[DataCenter instance] getStringForKey:@"loginsuccess"]];
            }else{
                [SVProgressHUD showErrorWithStatus:[[DataCenter instance] getStringForKey:@"loginfailed"]];
                NSLog(@"login：%@",respond.msg);
            }
        }];
    }
    [application registerForRemoteNotificationTypes: UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound];
    [self performSelector:@selector(netrequestDelay) withObject:nil afterDelay:1.0];

    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"applicationDidEnterBackground" object:nil];
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"applicationDidBecomeActive" object:nil];
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    if(![CLLocationManager locationServicesEnabled]){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"您未打开GPS" message:@"这将导致您不能很好的使用该软件" delegate:nil cancelButtonTitle:[[DataCenter instance] getStringForKey:@"Sure"] otherButtonTitles: nil];
        [alert show];
    }
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark -

-(void)netrequestDelay{
    //启动友盟统计
    [MobClick startWithAppkey:@"5332832556240bb26f0c9055"];
    [MobClick checkUpdate];
    
    //loading
    [ServiceManage loadingRequestcompletion:^(RespondDTO *respond) {
        
    }];
}

#pragma mark -  qq and wechat
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    if ([[url scheme] isEqualToString:[@"tencent" stringByAppendingString:qqKey]]) {
        return [QQApiInterface handleOpenURL:url delegate:self];
    }else if([[url scheme] isEqualToString:wxKey]){
        return  [WXApi handleOpenURL:url delegate:self];
    }else if ([[url scheme] isEqualToString:[@"sinaweibosso" stringByAppendingString:kAppKey]]){
        [[[SinaWeibo alloc] init] handleOpenURL:url];
    }
    return YES;
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    if ([[url scheme] isEqualToString:[@"tencent" stringByAppendingString:qqKey]]) {
        return [QQApiInterface handleOpenURL:url delegate:self];
    }else if([[url scheme] isEqualToString:wxKey]){
        return  [WXApi handleOpenURL:url delegate:self];
    }else if ([[url scheme] isEqualToString:[@"sinaweibosso" stringByAppendingString:kAppKey]]){
        [[[SinaWeibo alloc] init] handleOpenURL:url];
    }
    return YES;
}


#pragma mark wechat & qq

-(void)addShareLog:(int)tag{
    if ([DataCenter instance].user) {
        [ServiceManage shareRequestInfo:@{@"Mobile": [DataCenter instance].user.userPhone,@"ShareType":[NSString stringWithFormat:@"%d",tag]} completion:^(RespondDTO *respond) {
            NSLog(@"分享接口：%@",respond.msg);
        }];
    }
}

- (void)onResp:(id)resp{
    if ([resp isKindOfClass:[QQBaseResp class]]) {
        QQBaseResp *response = (QQBaseResp*)resp;
        if ([response.result integerValue] == 0) {
            [self addShareLog:1];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[[DataCenter instance] getStringForKey:@"Tips"] message:[[DataCenter instance] getStringForKey:@"ShareSuccess"] delegate:nil cancelButtonTitle:[[DataCenter instance] getStringForKey:@"Sure"] otherButtonTitles: nil];
            [alert show];
        }else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[[DataCenter instance] getStringForKey:@"Tips"] message:[[DataCenter instance] getStringForKey:@"ShareFailed"] delegate:nil cancelButtonTitle:[[DataCenter instance] getStringForKey:@"Sure"] otherButtonTitles: nil];
            [alert show];
        }
    }else{
        BaseResp *response = (BaseResp*)resp;
        
        switch (response.errCode) {
            case WXSuccess:{
                NSLog(@"成功");
                [self addShareLog:2];
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[[DataCenter instance] getStringForKey:@"Tips"] message:[[DataCenter instance] getStringForKey:@"ShareSuccess"] delegate:nil cancelButtonTitle:[[DataCenter instance] getStringForKey:@"Sure"] otherButtonTitles: nil];
                [alert show];
            }
                break;
//            case WXErrCodeUserCancel:{
//                NSLog(@"取消");
//                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[[DataCenter instance] getStringForKey:@"Tips"] message:@"已取消分享" delegate:nil cancelButtonTitle:[[DataCenter instance] getStringForKey:@"Sure"] otherButtonTitles: nil];
//                [alert show];
//            }
//                break;
            default:{
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[[DataCenter instance] getStringForKey:@"Tips"] message:[[DataCenter instance] getStringForKey:@"ShareFailed"] delegate:nil cancelButtonTitle:[[DataCenter instance] getStringForKey:@"Sure"] otherButtonTitles: nil];
                [alert show];
            }
                break;
        }
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:@"Resp" object:nil];
}

#pragma mark - baidu map
- (void)onGetNetworkState:(int)iError
{
    if (0 == iError) {
        NSLog(@"联网成功");
    }
    else{
        NSLog(@"onGetNetworkState %d",iError);
    }
    
}

- (void)onGetPermissionState:(int)iError
{
    if (0 == iError) {
        NSLog(@"授权成功");
    }
    else {
        NSLog(@"onGetPermissionState %d",iError);
    }
}

#pragma mark - QQ
/**
 * 登录成功后的回调
 */
- (void)tencentDidLogin{
    
}

/**
 * 登录失败后的回调
 * \param cancelled 代表用户是否主动退出登录
 */
- (void)tencentDidNotLogin:(BOOL)cancelled{
    
}

/**
 * 登录时网络有问题的回调
 */
- (void)tencentDidNotNetWork{
    
}

#pragma mark Push Notification
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSLog(@"deviceToken:%@", deviceToken);
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"didFailToRegisterForRemoteNotificationsWithError:%@", [[error userInfo] objectForKey:@"NSLocalizedDescription"]);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    NSLog(@"didReceiveRemoteNotification:%@", userInfo);
    NSDictionary *apsDict = [userInfo objectForKey:@"aps"];
    NSString *msg = apsDict[@"alert"];
    
    NSMutableArray *array = [NSMutableArray arrayWithContentsOfFile:MSGPATH];
    if (!array) {
        array = [NSMutableArray array];
    }
    [array insertObject:@{@"msg":msg,@"date":[NSDate date]} atIndex:0];
    [array writeToFile:MSGPATH atomically:YES];
    
    NSLog(@"%@",apsDict);
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}

#pragma mark -
-(void)netChanged:(NSNotification*)noti{
   NetworkStatus status = (NetworkStatus)[[[noti object] valueForKey:@"currentReachabilityStatus"] intValue];
    if (netalert) {
        [netalert dismissWithClickedButtonIndex:0 animated:YES];
    }
    if (status == NotReachable) {
         netalert = [[UIAlertView alloc] initWithTitle:[[DataCenter instance] getStringForKey:@"Tips"] message:@"当前网络已断开，将不能很好的体验该应用" delegate:nil cancelButtonTitle:[[DataCenter instance] getStringForKey:@"Sure"] otherButtonTitles: nil];
        [netalert show];
    }else {
//        netalert = [[UIAlertView alloc] initWithTitle:[[DataCenter instance] getStringForKey:@"Tips"] message:@"网络已恢复" delegate:nil cancelButtonTitle:[[DataCenter instance] getStringForKey:@"Sure"] otherButtonTitles: nil];
//        [netalert show];
    }
    
//    else if(status == ReachableViaWiFi){
//         netalert = [[UIAlertView alloc] initWithTitle:[[DataCenter instance] getStringForKey:@"Tips"] message:@"网络已切换到wifi状态" delegate:nil cancelButtonTitle:[[DataCenter instance] getStringForKey:@"Sure"] otherButtonTitles: nil];
//        [netalert show];
//    }else if(status == ReachableViaWWAN){
//        netalert = [[UIAlertView alloc] initWithTitle:[[DataCenter instance] getStringForKey:@"Tips"] message:@"网络已切换到Wan状态" delegate:nil cancelButtonTitle:[[DataCenter instance] getStringForKey:@"Sure"] otherButtonTitles: nil];
//        [netalert show];
//    }
}

@end
